package com.example.myapplication10_3;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    // 定义菜单组 ID 和子菜单项 ID
    private static final int GROUP_ID_ONE = 1;
    private static final int GROUP_ID_TWO = 2;
    private static final int SUBMENU_ITEM_1 = 1;
    private static final int SUBMENU_ITEM_2 = 2;
    private static final int SUBMENU_ITEM_3 = 3;
    private static final int SUBMENU_ITEM_4 = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // 创建选项菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 添加第一个父级菜单及其子菜单项
        SubMenu subMenuOne = menu.addSubMenu("菜单一");
        subMenuOne.add(GROUP_ID_ONE, SUBMENU_ITEM_1, Menu.NONE, R.string.sub_menu_item_1);
        subMenuOne.add(GROUP_ID_ONE, SUBMENU_ITEM_2, Menu.NONE, R.string.sub_menu_item_2);

        // 添加第二个父级菜单及其子菜单项
        SubMenu subMenuTwo = menu.addSubMenu("菜单二");
        subMenuTwo.add(GROUP_ID_TWO, SUBMENU_ITEM_3, Menu.NONE, R.string.sub_menu_item_3);
        subMenuTwo.add(GROUP_ID_TWO, SUBMENU_ITEM_4, Menu.NONE, R.string.sub_menu_item_4);

        return true;
    }

    // 响应菜单项点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId != 0) { // 如果不是父级菜单，即子菜单
            String tstStr = "选中的是菜单“"
                    + item.getGroupId() + "”中的子菜单项" + itemId;
            Toast.makeText(this, tstStr, Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);
    }
}